package xyz.chaobei.config;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 权限切面，通过关键词切入到controller里面的所有方法
 */
@Aspect
@Component
public class PermissionAsp {

    Logger logger = LoggerFactory.getLogger(PermissionAsp.class);

    @Pointcut("execution(public * xyz.chaobei.controller.*.*(..))")
    public void controllerCut(){}

    /**
     * 环绕切面通知
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("controllerCut()")
    public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        Object result = null;

        //通过注解拿出对应的权限域；
        RequestMapping requestMapping = proceedingJoinPoint.getTarget().getClass().getAnnotation(RequestMapping.class);

        if (requestMapping == null) {
            //直接断开方法的执行
            return null;
        }
        String name = proceedingJoinPoint.getSignature().getName();
        String group = requestMapping.value()[0];

        String permission = group+":"+name;

        Subject currentUser = SecurityUtils.getSubject();

        //currentUser.checkPermission(permission);

        /*proceed()方法表示连接点方法执行 result 为连接点方法的返回值*/
        result = proceedingJoinPoint.proceed();

        return result;
    }




}